# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import fields, models, api

import logging
_logger = logging.getLogger(__name__)



class IotSensor(models.Model):
    _inherit = "iot.sensor"

    @api.model
    def update_sensors(self, device, sensors):
        for sensor in sensors:
            obj = self.search_by_code(sensor.get('code'))

            values = {
                'device_id': device.id,
                'code': sensor.get('code'), 
                'name': sensor.get('name'), 
                'depth': sensor.get('depth'), 
                'sensor_type_id': self.env['iot.sensor.type'
                    ].search_by_code( sensor.get('sensor_type') ).id

            }

            if not obj:
                obj = obj.create(values)
            else:
                obj.write(values)


class IotValue(models.Model):
    _inherit = "iot.value"

    @api.model
    def update_values(self, sensors):
        
        value_list = []
        
        for sensor in sensors:
            sensor_id = self.sensor_id.search_by_code(sensor.get('code'))

            if not sensor_id:
                # server and gateway is not same config. 
                continue

            values = {
                'code': sensor.get('code'), 
                'sensor_id': sensor_id.id,
                'device_id': sensor_id.device_id.id,
                'gateway_id': sensor_id.gateway_id.id,
                'project_id': sensor_id.project_id.id,
                'latitude': sensor_id.latitude, 
                'longitude': sensor_id.longitude, 
                'sensor_type_id': sensor_id.sensor_type_id.id,
                'depth': sensor_id.depth, 
                'time': sensor.get('time'), 
                'value': sensor.get('value'), 
            }

            value_list.append(values)
            
        if value_list:
            return self.create(value_list)

        return self

